package com.cmc.cloud.cmclink.doc.service.impl.si;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoPaymentErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.BlnoPaymentConvert;
import com.cmc.cloud.cmclink.doc.entity.BlnoPaymentDO;
import com.cmc.cloud.cmclink.doc.mapper.BlnoPaymentMapper;
import com.cmc.cloud.cmclink.doc.service.si.BlnoPaymentService;
import com.cmc.cloud.cmclink.doc.vo.blnopaymentvo.BlnoPaymentCreateReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnopaymentvo.BlnoPaymentPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnopaymentvo.BlnoPaymentUpdateReqVO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 提单指定支付方式信息 Service 实现类
 *
 * @author 集运管理员
 */
@Service
@Validated
public class BlnoPaymentServiceImpl implements BlnoPaymentService {

    @Resource
    private BlnoPaymentMapper blnoPaymentMapper;

    @Override
    public void createBlnoPayment(BlnoPaymentCreateReqVO createReqVO) {
        // 插入
        BlnoPaymentDO blnoPayment = BlnoPaymentConvert.INSTANCE.convert(createReqVO);
        blnoPaymentMapper.insert(blnoPayment);
    }

    @Override
    public void updateBlnoPayment(BlnoPaymentUpdateReqVO updateReqVO) {
        // 校验存在
        validateBlnoPaymentExists(updateReqVO.getId());
        // 更新
        BlnoPaymentDO updateObj = BlnoPaymentConvert.INSTANCE.convert(updateReqVO);
        blnoPaymentMapper.updateById(updateObj);
    }

    @Override
    public void deleteBlnoPayment(Long id) {
        // 校验存在
        validateBlnoPaymentExists(id);
        // 删除
        blnoPaymentMapper.deleteById(id);
    }

    @Override
    public void deleteBlnoPaymentByblnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoPaymentDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoPaymentDO::getBlnoId, blnoId);
        blnoPaymentMapper.delete(queryWrapper);
    }

    private void validateBlnoPaymentExists(Long id) {
        if (blnoPaymentMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(BlnoPaymentErrorCodeConstants.BLNO_PAYMENT_NOT_EXISTS);
        }
    }

    @Override
    public BlnoPaymentDO getBlnoPayment(Long id) {
        return blnoPaymentMapper.selectById(id);
    }

    @Override
    public List<BlnoPaymentDO> getBlnoPaymentsByBlnoId(Long id) {
        LambdaQueryWrapper<BlnoPaymentDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoPaymentDO::getBlnoId, id);
        queryWrapper.orderByAsc(BlnoPaymentDO::getId);
        return blnoPaymentMapper.selectList(queryWrapper);
    }

    @Override
    public List<BlnoPaymentDO> getBlnoPaymentsByBlnoIds(List<Long> ids) {
        LambdaQueryWrapper<BlnoPaymentDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BlnoPaymentDO::getBlnoId, ids);
        queryWrapper.orderByAsc(BlnoPaymentDO::getId);
        return blnoPaymentMapper.selectList(queryWrapper);
    }

    @Override
    public List<BlnoPaymentDO> getBlnoPaymentList(Collection<Long> ids) {
        return blnoPaymentMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlnoPaymentDO> getBlnoPaymentPage(BlnoPaymentPageReqVO reqVO) {
        IPage<BlnoPaymentDO> page = Page.of(reqVO.getPageNo(), reqVO.getPageSize());

        IPage<BlnoPaymentDO> result = blnoPaymentMapper.selectPageList(page, reqVO);
        return new PageResult<BlnoPaymentDO>(result.getRecords(), result.getTotal());
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long blnoId, List<BlnoPaymentUpdateReqVO> newList, List<BlnoPaymentUpdateReqVO> oldList) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<BlnoPaymentUpdateReqVO> createList = new ArrayList<>();
        List<BlnoPaymentUpdateReqVO> updateList = new ArrayList<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                    // 数据更新非法
                    throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_NI_UPDATE);
                }
            } else {
                e.setBlnoId(blnoId);
                createList.add(e);
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            blnoPaymentMapper.deleteBatchIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<BlnoPaymentDO> siPaymentCreateList = BeanUtil.copyToList(createList, BlnoPaymentDO.class);
            blnoPaymentMapper.insertBatch(siPaymentCreateList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<BlnoPaymentDO> siPaymentUpdateList = BeanUtil.copyToList(updateList, BlnoPaymentDO.class);
            blnoPaymentMapper.updateBatch(siPaymentUpdateList);
        }
    }
}
